package com.ahsjdy.st.stbocustomer.controller;

import com.ahsjdy.st.stbocustomer.util.IPUtils;
import com.ahsjdy.st.stservice.pay.NotifyHolder;
import com.ahsjdy.st.stservice.pay.WxpayHandler;
import com.ahsjdy.stcommon.dto.ResponseDTO;
import com.ahsjdy.stcommon.exception.BizException;
import com.ahsjdy.stcommon.vo.SettleInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Description
 * @Author xuetao wang
 * @Date 2020/2/5
 */
@RestController
public class OrderController extends BaseController {

    @Autowired
    private CustomerServiceImpl customerService;

    @Autowired
    private WxpayHandler wxpayHandler;

    @RequestMapping(value = "/customer/settleOrder")
    public ResponseDTO settleOrder(String openId, int merchantId, String settleInfo) {
        return ResponseDTO.success(customerService.settleOrder(openId, merchantId, settleInfo));
    }

    @RequestMapping(value = "/customer/loadSettle")
    public ResponseDTO loadSettle(String openId, String bizOrderId) {
        return ResponseDTO.success(customerService.loadSettle(openId, bizOrderId));
    }

    @RequestMapping(value = "/customer/toPay")
    public ResponseDTO toPay(SettleInfoVO settleInfoVO) {
        return ResponseDTO.success(customerService.updateSettleDetail(settleInfoVO, IPUtils.getIpAddr(request)));
    }

    @RequestMapping(value = "/customer/refundOrder")
    public ResponseDTO refundOrder(String openId, String bizOrderId) {
        customerService.refundOrder(openId, bizOrderId);
        return ResponseDTO.success();
    }

    @RequestMapping(value = "/wxpay/notify")
    public void wxpayNotify(HttpServletRequest request, HttpServletResponse response) {
        logger.info(">>>>>>>>>微信异步通知开始");
        BufferedReader br = null;
        String xmlMsg = "";
        String readStr = null;
        OutputStream os = null;
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");

            br = request.getReader();

            while ((readStr = br.readLine()) != null) {
                xmlMsg += readStr;
            }

            logger.info(">>>>>>>>>微信异步通知参数：" + xmlMsg);
            NotifyHolder resultMap = wxpayHandler.notifyProcess(xmlMsg);
            if (!resultMap.isSuccess()) {
                throw new BizException("异步支付停止异常");
            }

            String orderAmount = resultMap.getTotalAmount();
            System.out.println("支付金额=" + orderAmount);

            String orderId = resultMap.getOutTradeNo();

            customerService.payNotify(orderId, orderAmount);

            os = response.getOutputStream();
            os.write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>".getBytes());
            os.flush();
            logger.info(">>>>>>>微信异步通知结束");

        } catch (Exception e) {
            logger.error("处理微信异步通知异常，" + e.getMessage(), e);
            if (os == null) {
                return;
            }
            try {
                os.write("<xml><return_code><![CDATA[FAIL]]></return_code></xml>".getBytes());
                os.flush();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                }
            }

            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                }
            }
        }

    }


    @RequestMapping(value = "/wxpay/refundNotify")
    public void wxRefundNotify(HttpServletRequest request, HttpServletResponse response) {
        logger.info(">>>>>>>>>微信退款通知开始");
        BufferedReader br = null;
        String xmlMsg = "";
        String readStr = null;
        OutputStream os = null;
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");

            br = request.getReader();

            while ((readStr = br.readLine()) != null) {
                xmlMsg += readStr;
            }

            logger.info(">>>>>>>>>微信退款通知参数：" + xmlMsg);
            NotifyHolder resultMap = wxpayHandler.notifyRefundProcess(xmlMsg);
            if (!resultMap.isSuccess()) {
                throw new BizException("微信退款异常");
            }

            String orderAmount = resultMap.getTotalAmount();
            System.out.println("支付退款金额=" + orderAmount);

            String orderId = resultMap.getOutTradeNo();

            customerService.refundOrderNotify(orderId);

            os = response.getOutputStream();
            os.write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>".getBytes());
            os.flush();
            logger.info(">>>>>>>微信退款通知结束");

        } catch (Exception e) {
            logger.error("处理微信退款通知异常，" + e.getMessage(), e);
            if (os == null) {
                return;
            }
            try {
                os.write("<xml><return_code><![CDATA[FAIL]]></return_code></xml>".getBytes());
                os.flush();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                }
            }

            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                }
            }
        }

    }
}
